package cn.kgc.ssm.interceptors;

import cn.kgc.ssm.entity.User;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.util.Objects;

/**
 * @author 课工场
 * @date 2023/10/25
 * @description  登录拦截器   实现非法请求拦截
 */
public class LoginInterceptor implements HandlerInterceptor {

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {

        // 判定用户是否已经完成了登录操作
        HttpSession session = request.getSession();
        User user = (User) session.getAttribute("user");

        if (Objects.isNull(user)){  //  非法请求
            // 重定向页面到登录页
            response.sendRedirect(request.getContextPath()+"/login.html");
            return  false;
        }

        return  true;
    }
}
